/**
 * @(#)MailSubscribeController.java, 2010-5-16. 
 * 
 * Copyright 2010 Youdao, Inc. All rights reserved.
 * YOUDAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.rsstuan.web.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.log.Log;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.rsstuan.storage.data.MailSubscribeData;
import com.rsstuan.storage.impl.JDOMailSubscribeStorage;
import com.rsstuan.utils.CityUtils;

/**
 *
 * @author guosq
 *
 */
public class MailSubscribeController extends SpringController {

	private Logger LOG = Logger.getLogger(MailSubscribeController.class.getName());
    private JDOMailSubscribeStorage storage = new JDOMailSubscribeStorage();
    
    private String RESULT_VM = "main/result";
    
    private String EMAIL_VM = "main/email";
    
    public ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) {
    
        MailSubscribeData sub = new MailSubscribeData();
        String email = request.getParameter("email");
        String cityid = request.getParameter("cityid");
        String city = CityUtils.getCityString(cityid);
        Map<String, Object> model = new HashMap<String,Object>();
        model.put("email", email);
        model.put("city", city);
        try {
            sub.setEmail(email);
            sub.setCity(city);
            sub.setSubTime(System.currentTimeMillis());
            sub.setLastSentTime(0);
            
            model.put("title", "订阅邮件成功");
            model.put("content", "订阅邮件成功, 非常感谢您的支持！");
            if (storage.exist(email, city)) {
            	model.put("status", "subscribed");
            }
            else {
            boolean ret = storage.save(sub);
            if (!ret) {
	            	model.put("status", "failed");
					LOG.log(Level.WARNING, "subscribe failed, email=" + email
							+ " cityid=" + cityid);
				} else {
					model.put("status", "sucess");
					LOG.info("subscribe success, email=" + email + " cityid="
							+ cityid);
				}
            }
           
        }
        catch (Exception e) {
        	LOG.log(Level.WARNING, "subscribe failed, email=" + email + " cityid=" + cityid, e);
        }
        
        return createModelAndView(request, response, RESULT_VM, model);
        
    }
    
    public ModelAndView showForm(HttpServletRequest request,
            HttpServletResponse response) {
    	 Map<String, Object> model = new HashMap<String,Object>();
    	 return createModelAndView(request, response, EMAIL_VM, model);
    	
    }
    
}
